﻿/*
 * Сделано в SharpDevelop.
 * Пользователь: maxxadm
 * Дата: 18.09.2012
 * Время: 20:07
 * 
 * Для изменения этого шаблона используйте Сервис | Настройка | Кодирование | Правка стандартных заголовков.
 */
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.CompilerServices;

namespace jellybird
{
	
		

	public static class ListBoxExtension
	{
		/*
		 * http://www.dominikschmidt.net/2011/01/netc-first-visible-item-listbox-attached-behavior/
		 */
		
		/// <summary>
		/// Sets the first visible item (i.e., scrolls to make
		/// given item the first visible).
		/// </summary>
		/// <param name="listBox">The ListBox</param>
		/// <param name="item">The item to be the first visible</param>
		public static void SetFirstVisibleItem(this ListBox listBox, object item)
		{
			PerformScroll(listBox, item);
		}

		/// <summary>
		/// Gets the first visible item.
		/// </summary>
		/// <param name="listBox">The ListBox</param>
		/// <returns>The first visible item or null of there are no items</returns>
		
		public static object GetFirstVisibleItem(this ListBox listBox)
		{
			return listBox.Items.Count > 0 ?
				listBox.Items[listBox.GetPanelOffset()] : null;
		}

		/// <summary>
		/// Gets horizontal or vertical offset (depending on panel orientation).
		/// </summary>
		/// <param name="listBox">The ListBox</param>
		/// <returns>The offset or 0 if no VirtualizingStackPanel was found</returns>
		
		private static int GetPanelOffset(this ListBox listBox)
		{
			VirtualizingStackPanel panel = listBox.GetPanel();
			if (panel != null)
				return (int)((panel.Orientation == Orientation.Horizontal) ? panel.HorizontalOffset : panel.VerticalOffset);
			else
				return 0;
		}

		/// <summary>
		/// Sets horizontal or vertical offset depending on panel orientation.
		/// </summary>
		/// <param name="listBox">The ListBox</param>
		/// <param name="offset">The offset</param>
		
		private static void SetPanelOffset(this ListBox listBox, int offset)
		{
			VirtualizingStackPanel panel = listBox.GetPanel();
			if (panel != null)
			{
				if (panel.Orientation == Orientation.Horizontal)
					panel.SetHorizontalOffset(offset);
				else
					panel.SetVerticalOffset(offset);
			}
		}

		/// <summary>
		/// Retrieves the ListBox's items panel as VirtualizingStackPanel.
		/// </summary>
		/// <param name="listBox">The ListBox</param>
		/// <returns>The item panel or null if no VirtualizingStackPanel was found</returns>
		
		public static VirtualizingStackPanel GetPanel(this ListBox listBox)
		{
			VirtualizingStackPanel panel = VisualHelpers.TryFindChild<VirtualizingStackPanel>(listBox);
			if (panel == null)
				Debug.WriteLine("No VirtualizingStackPanel found for ListBox.");
			return panel;
		}

		/// <summary>
		/// Brings requested item into view as first visible item.
		/// </summary>
		/// <param name="listBox">The ListBox</param>
		/// <param name="item">The requested item</param>
		private static void PerformScroll(ListBox listBox, object item)
		{
			// get container for requested item
			DependencyObject container = listBox.ItemContainerGenerator.ContainerFromItem(item);

			// container does not exist yet (for example because it is not yet in view)
			if (container == null)
			{
				// scroll item into view...
				listBox.ScrollIntoView(item);
				// ...and get its container
				container = listBox.ItemContainerGenerator.ContainerFromItem(item);
			}

			// double-check that container was retrieved
			if (container != null)
			{
				// make sure that item is not only in view,
				// but that it is indeed the first item visible
				int index = listBox.ItemContainerGenerator.IndexFromContainer(container);

				// if panel offset is not equal to index, the
				// item is in view, but not as first item
				if (listBox.GetPanelOffset() != index)
					listBox.SetPanelOffset(index);
			}
		}
	}
	
	
	public static class VisualHelpers
    {
        /// <summary>
        /// Finds a parent of a given item on the visual tree.
        /// </summary>
        /// <typeparam name="T">The type of the queried item.</typeparam>
        /// <param name="child">A direct or indirect child of the
        /// queried item.</param>
        /// <returns>The first parent item that matches the submitted
        /// type parameter. If not matching item can be found, a null
        /// reference is being returned.</returns>
		
        public static T TryFindParent<T>(this DependencyObject child)
            where T : DependencyObject
        {
            //get parent item
            DependencyObject parentObject = GetParentObject(child);

            //we've reached the end of the tree
            if (parentObject == null) return null;

            //check if the parent matches the type we're looking for
            T parent = parentObject as T;
            if (parent != null)
            {
                return parent;
            }
            else
            {
                //use recursion to proceed with next level
                return TryFindParent<T>(parentObject);
            }
        }

        /// <summary>
        /// Finds a child of the given item on the visual tree.
        /// </summary>
        /// <typeparam name="T">The type of the queried item.</typeparam>
        /// <param name="parent">A parent of the queried item.</param>
        /// <returns>The first child item that matches the submitted
        /// type parameter. If not matching item can be found, a null
        /// reference is being returned.</returns>
		
        public static T TryFindChild<T>(this DependencyObject parent) 
            where T : DependencyObject
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
            {
                DependencyObject child = VisualTreeHelper.GetChild(parent, i);

                if (child is T)
                {
                    return (T)child;
                }
                else
                {
                    child = TryFindChild<T>(child);
                    if (child != null)
                    {
                        return (T)child;
                    }
                }
            }
            return null;
        } 

        /// <summary>
        /// This method is an alternative to WPF's
        /// <see cref="VisualTreeHelper.GetParent"/> method, which also
        /// supports content elements. Keep in mind that for content element,
        /// this method falls back to the logical tree of the element!
        /// </summary>
        /// <param name="child">The item to be processed.</param>
        /// <returns>The submitted item's parent, if available. Otherwise
        /// null.</returns>
		
        public static DependencyObject GetParentObject(this DependencyObject child)
        {
            if (child == null) return null;

            //handle content elements separately
            ContentElement contentElement = child as ContentElement;
            if (contentElement != null)
            {
                DependencyObject parent = ContentOperations.GetParent(contentElement);
                if (parent != null) return parent;

                FrameworkContentElement fce = contentElement as FrameworkContentElement;
                return fce != null ? fce.Parent : null;
            }

            //also try searching for parent in framework elements (such as DockPanel, etc)
            FrameworkElement frameworkElement = child as FrameworkElement;
            if (frameworkElement != null)
            {
                DependencyObject parent = frameworkElement.Parent;
                if (parent != null) return parent;
            }

            //if it's not a ContentElement/FrameworkElement, rely on VisualTreeHelper
            return VisualTreeHelper.GetParent(child);
        }
    }
}
